<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\ChatRoom as ChatRoomModel;
use app\common\model\InquiryForm as InquiryFormModel;
use app\common\model\InquiryPrice as InquiryPriceModel;
use app\common\model\ChatGroup as ChatGroupModel;
use app\admin\model\User as UserModel;
use app\common\model\ChatGroupContent as ChatGroupContentModel;
use think\Validate;
use think\Db;

class Offer extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';

    /**
     * 发布询价
     * @ApiMethod (POST)
     * @path api/offer/publishInquiry
     */
    public function publishInquiry()
    {
        if(!$this->request->isPost()) {
            $this->error('请求失败，请使用POST方式请求');
        }
        $params = $this->request->param();
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if(!$params){
            $this->error("非法传参");
        }
        $data = [
            'group_id'=>$params["group_id"], //群id
            'title'=>$params["title"], //标题
            'content'=>$params["content"], //内容
            'images'=>$params["images"], //图片
        ];

        $role = [
            'group_id' => 'require',
            'title' => 'require',
            'content' => 'require',
            'images'=>'require',
        ];

        $msg = [
            'group_id.require'=>'群ID不能为空',
            'title.require'=>'标题不能为空',
            'content.require'=>'内容不能为空',
            'images.require'=>'图片不能为空',
        ];
        $validate = new Validate($role,$msg);   //$role效验规则   $msg规则错误时返回
        if(!$validate->check($data))$this->error($validate->getError());
        if(isset($params["images"]) && !empty($params["images"])){
            $content_images = explode(",",$params["images"]);
            foreach ($content_images as $key=>&$value){
                $value = parse_url($value)["path"];
            }
            $content_images_str = implode(",",$content_images);
        }else{
            $content_images_str = "";
        }
        $info = InquiryFormModel::where(["group_id"=>$data['group_id'],"user_id"=>$user_id])->find();
        if($info){
            $this->error("询价已存在");
        }
        $data['images'] = $content_images_str;
        $data["user_id"] = $user_id;
        $data["is_bid"] = 1;
        $data["bid_user"] = 0;
        $data["add_time"] = time();
        $res = InquiryFormModel::create($data);
        $chat_group_info = ChatGroupModel::get($data['group_id']);
        $where = "to_id = {$data['group_id']}";
        $where.= " AND information_id = '0'";
        $where.= " AND group_type = '2'";
        $room_info = ChatRoomModel::where($where)->find();
        $room_id_arr = ChatRoomModel::where($where)->column("id");
        if($room_id_arr){
            $room_id_str = implode(",",$room_id_arr);
        }else{
            $room_id_str = "";
        }
        $group_data = [];
        $group_data['group_id'] = $data['group_id'];
        $group_data['user_id'] = $user_id;
        $group_data['room_ids'] = $room_id_str;
        $group_data['content'] = "我发布了一份询价单需要您填写";
        $group_data['first_line'] = "我发布了一份询价单需要您填写";
        $group_data['second_line'] = "点击查看";
        $group_data['type'] = 4;
        $group_data['add_time'] = time();
        $msg_id = Db::name("chat_group_content")->insertGetId($group_data);
        ChatRoomModel::where(["group_room"=>$data['group_id'],"is_margin"=>1])->setInc("number",1);
        if($res){
            //消息中心
            $list = ChatRoomModel::chat_content_info($user_id,$data["group_id"],2);
            $is_margin = ChatRoomModel::where(["group_room"=>$data["group_id"],"is_margin"=>1])->column("user_id");
            $list['is_margin'] = $is_margin;
            $list['type'] = 4;
            $list["first_line"] = "我发布了一份询价单需要您填写";
            $list["second_line"] = "点击查看";
            $list['content'] = "我发布了一份询价单需要您填写";
            $list['last_time'] = getChatTimeStr(time());
            //聊天内容
            $info = ChatGroupContentModel::get_content_info($msg_id,$room_info->id);
            $info['type'] = 4;
            $info['first_line'] = "我发布了一份询价单需要您填写";
            $info["second_line"] = "点击查看";
            $info["group_room"] = $data["group_id"];
            $content = [
                "list" => $list,
                "info" => $info,
            ];
            ChatRoomModel::sendToGroup($user->identification,$chat_group_info->h_id,$content);
            ChatRoomModel::where($where)->update(["content"=>"我发布了一份询价单需要您填写","group_room"=>$data['group_id'],"last_time"=>time()]);
            $this->success("发布询价成功");
        }else{
            $this->error("发布询价失败");
        }
    }

    /**
     * 填写询价
     * @ApiMethod (POST)
     * @path api/offer/writeInquiry
     */
    public function writeInquiry()
    {
        if(!$this->request->isPost()) {
            $this->error('请求失败，请使用POST方式请求');
        }
        $params = $this->request->param();
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        if(!$params){
            $this->error("非法传参");
        }
        $data = [
            'inquiry_id'=>$params["inquiry_id"], //询价单id
            'price'=>$params["price"], //价格
        ];

        $role = [
            'inquiry_id' => 'require',
            'price' => 'require',
        ];

        $msg = [
            'inquiry_id.require'=>'询价单ID不能为空',
            'price.require'=>'价格不能为空',
        ];
        $validate = new Validate($role,$msg);   //$role效验规则   $msg规则错误时返回
        if(!$validate->check($data))$this->error($validate->getError());
        $inquiry_info = InquiryFormModel::get($data['inquiry_id']);
        if(!$inquiry_info){
            $this->error("询价信息错误");
        }
        $info = InquiryPriceModel::where(["user_id"=>$user_id,"inquiry_id"=>$data['inquiry_id']])->find();
        if($info){
            $this->error("报价信息已存在");
        }
        $data["user_id"] = $user_id;
        $data["is_bid"] = 1;
        $data["add_time"] = time();
        $res = InquiryPriceModel::create($data);
        $chat_group_info = ChatGroupModel::get($inquiry_info['group_id']);
        $where = "to_id = {$inquiry_info['group_id']}";
        $where.= " AND information_id = '0'";
        $where.= " AND group_type = '2'";
        $room_info = ChatRoomModel::where($where)->find();
        $room_id_arr = ChatRoomModel::where($where)->column("id");
        if($room_id_arr){
            $room_id_str = implode(",",$room_id_arr);
        }else{
            $room_id_str = "";
        }
        $group_data = [];
        $group_data['group_id'] = $inquiry_info['group_id'];
        $group_data['user_id'] = $user_id;
        $group_data['room_ids'] = $room_id_str;
        $group_data['content'] = "我填写了报价单 请您查看";
        $group_data['first_line'] = "我填写了报价单 请您查看";
        $group_data['second_line'] = "点击查看";
        $group_data['type'] = 5;
        $group_data['add_time'] = time();
        $msg_id = Db::name("chat_group_content")->insertGetId($group_data);
        ChatRoomModel::where(["group_room"=>$inquiry_info['group_id'],"is_margin"=>1])->setInc("number",1);
        if($res){
            //消息中心
            $list = ChatRoomModel::chat_content_info($user_id,$inquiry_info["group_id"],2);
            $is_margin = ChatRoomModel::where(["group_room"=>$inquiry_info["group_id"],"is_margin"=>1])->column("user_id");
            $list['is_margin'] = $is_margin;
            $list['type'] = 5;
            $list["first_line"] = "我填写了报价单 请您查看";
            $list["second_line"] = "点击查看";
            $list["group_room"] = $inquiry_info['group_id'];
            $list['content'] = "我填写了报价单 请您查看";
            $list['last_time'] = getChatTimeStr(time());
            //聊天内容
            $info = ChatGroupContentModel::get_content_info($msg_id,$room_info->id);
            $info['type'] = 5;
            $info['first_line'] = "我填写了报价单 请您查看";
            $info["second_line"] = "点击查看";
            $info["group_room"] = $inquiry_info['group_id'];
            $content = [
                "list" => $list,
                "info" => $info,
            ];
            ChatRoomModel::sendToGroup($user->identification,$chat_group_info->h_id,$content);
            ChatRoomModel::where($where)->update(["content"=>"我填写了报价单 请您查看","group_room"=>$inquiry_info['group_id'],"last_time"=>time()]);
            $this->success("填写询价成功");
        }else{
            $this->error("填写询价失败");
        }
    }

    /**
     * 询价信息
     * @ApiMethod (POST)
     * @path api/offer/inquiryInfo
     */
    public function inquiryInfo()
    {
        $user_id = $this->auth->user_id;
        $group_id = $this->request->param("group_id");
        if(!$group_id){
            $this->error("群id不能为空");
        }
        $info = InquiryFormModel::inquiry_form_info($group_id);
        if($info){
            $price_info = InquiryPriceModel::where(["user_id"=>$user_id,"inquiry_id"=>$info['id']])->order("id","DESC")->find();
            if($price_info){
                $info['price_id'] = $price_info['id'];
                $info['price'] = $price_info['price'];
            }
        }else{
            $info['price_id'] = '';
            $info['price'] = '';
        }
        $this->success("请求成功",$info);
    }

    /**
     * 修改询价
     * @ApiMethod (POST)
     * @path api/offer/inquiryModify
     */
    public function inquiryModify()
    {
        $price_id = $this->request->param("price_id");
        $price = $this->request->param("price");
        if(!$price_id){
            $this->error("报价单id不能为空");
        }
        if(!$price){
            $this->error("价格不能为空");
        }
        $user_id = $this->auth->user_id;
        $where = "user_id = {$user_id}";
        $where.= " AND id = {$price_id}";
        $order = "id DESC";
        $price_info = InquiryPriceModel::where($where)->order($order)->find();
        if(!$price_info){
            $this->error("信息错误");
        }
        if($price <= $price_info->price){
            $this->error("请大于原来的报价金额");
        }
        $price_info->price = $price;
        $price_info->save();
        $this->success("报价金额成功");
    }

    /**
     * 报价单排行
     * @ApiMethod (POST)
     * @path api/offer/offerRanking
     */
    public function offerRanking()
    {
        $group_id = $this->request->param("group_id");
        $page = $this->request->param("page",1);
        if(!$group_id){
            $this->error("群ID不能为空");
        }
        $info = InquiryFormModel::inquiry_form_info($group_id);
        if(!$info){
            $this->error("询价信息错误");
        }
        $list = InquiryPriceModel::get_price_list($page,$info->id);
        $this->success("请求成功",$list);
    }

    /**
     * 确认选择
     * @ApiMethod (POST)
     * @path api/offer/confirmSelection
     */
    public function confirmSelection()
    {
        $price_id = $this->request->param("price_id");
        $user_id = $this->request->param("user_id");
        $user = $this->auth->getUser();
        if(!$price_id){
            $this->error("报价单id不能为空");
        }
        if(!$user_id){
            $this->error("成交用户id不能为空");
        }
        $where = "id = {$price_id}";
        $price_info = InquiryPriceModel::where($where)->find();
        $inquiry_id = $price_info->inquiry_id;
        if(!$inquiry_id){
            $this->error("信息错误");
        }
        $group_info = InquiryFormModel::alias("if")->join("chat_group cg","if.group_id = cg.id")
            ->where("if.id",$inquiry_id)
            ->find();
        if($group_info){
            if($group_info['user_ids']){
                $user_id_arr = explode(",",$group_info['user_ids']);
                if(!in_array($user_id,$user_id_arr)){
                    $this->error("该用户已不在此群");
                }
            }
            $inquiry_form = Db::name("inquiry_form")->where(["group_id"=>$group_info['id'],"is_bid"=>'2'])->find();
            if($inquiry_form){
                $this->error("已成交,不可再次选择");
            }
            ChatGroupModel::where("id",$group_info['id'])->update(["is_bid"=>2]);
            $group_identification = UserModel::where("user_id",$group_info['user_id'])->value("identification");
        }
        $price_info->is_bid = 2;
        $price_info->save();
        $res = InquiryFormModel::where("id",$inquiry_id)->update(["is_bid"=>2,"bid_user"=>$user_id,"bid_price"=>$price_info->price]);
        $chat_group_info = ChatGroupModel::get($group_info['group_id']);
        $where = "to_id = {$group_info['group_id']}";
        $where.= " AND information_id = '0'";
        $where.= " AND group_type = '2'";
        $room_info = ChatRoomModel::where($where)->find();
        $room_id_arr = ChatRoomModel::where($where)->column("id");
        if($room_id_arr){
            $room_id_str = implode(",",$room_id_arr);
        }else{
            $room_id_str = "";
        }
        $group_data = [];
        $group_data['group_id'] = $group_info['group_id'];
        $group_data['user_id'] = $group_info['user_id'];
        $group_data['room_ids'] = $room_id_str;
        $group_data['content'] = "报价单已成交";
        $group_data['type'] = 14;
        $group_data['add_time'] = time();
        $msg_id = Db::name("chat_group_content")->insertGetId($group_data);
        ChatRoomModel::where(["group_room"=>$group_info['group_id'],"is_margin"=>1])->setInc("number",1);
        if($res){
            //消息中心
            $list = ChatRoomModel::chat_content_info($user_id,$group_info["group_id"],2);
            $is_margin = ChatRoomModel::where(["group_room"=>$group_info["group_id"],"is_margin"=>1])->column("user_id");
            $list['is_margin'] = $is_margin;
            $list['type'] = 14;
            $list["first_line"] = "报价单已成交";
            $list["second_line"] = "点击查看";
            $list['content'] = "报价单已成交";
            $list['last_time'] = getChatTimeStr(time());
            //聊天内容
            $info = ChatGroupContentModel::get_content_info($msg_id,$room_info->id);
            $info['type'] = 14;
            $info['first_line'] = "报价单已成交";
            $info["second_line"] = "点击查看";
            $info["group_room"] = $group_info["group_id"];
            $content = [
                "list" => $list,
                "info" => $info,
            ];
            ChatRoomModel::sendToGroup($group_identification,$chat_group_info->h_id,$content);
            ChatRoomModel::where($where)->update(["content"=>"报价单已成交","group_room"=>$group_info['group_id'],"last_time"=>time()]);
            $this->success("选择成功");
        }else{
            $this->error("选择失败");
        }
    }



}
